package com.example.hasee.plant.activity;

import android.app.Activity;
import android.content.Intent;
import android.hardware.Camera;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.hasee.plant.R;
import com.example.hasee.plant.config.MyApplication;

import java.io.File;
import java.util.Calendar;

/**
 * Created by jyb on 2017/2/2.
 */

public class TestBasicVideo extends Activity implements SurfaceHolder.Callback{
    private static final String TAG = "MainActivity";
    private SurfaceView mSurfaceview;
    private boolean mStartedFlg = false;//是否正在录像
    private boolean mIsPlay = false;//是否正在播放录像
    private MediaRecorder mRecorder;
    private SurfaceHolder mSurfaceHolder;
//    private ImageView mImageView;
    private Camera camera;
    private MediaPlayer mediaPlayer;
    private String path;
    private TextView textView;
    private int text = 0;
    private ImageButton iv_video;
    private TextView tv_back;

    private boolean isPlay;//判断是否为播放跳转过来的

    private android.os.Handler handler = new android.os.Handler();
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            text++;
            textView.setText(text+"");
            handler.postDelayed(this,1000);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.basevideo);

        tv_back= (TextView) findViewById(R.id.iv_back);
        iv_video= (ImageButton) findViewById(R.id.ib_video);
        mSurfaceview = (SurfaceView) findViewById(R.id.surfaceview);
        textView = (TextView)findViewById(R.id.text);
        isPlay=getIntent().getBooleanExtra("isPlay",false);
        path=getIntent().getStringExtra("videoPath");

        onListener();

        SurfaceHolder holder = mSurfaceview.getHolder();
        holder.addCallback(this);
        // setType必须设置，要不出错.
        holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

        if(isPlay){
            iv_video.setVisibility(View.GONE);
            textView.setVisibility(View.GONE);
            new Handler(){
                @Override
                public void handleMessage(Message msg) {
                    super.handleMessage(msg);
                    playVideo();
                }
            }.sendEmptyMessageDelayed(0,1000);
        }
    }


    private void onListener(){
        tv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onBackPressed();
            }
        });
        //录制视频按钮
        iv_video.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {

                switch (motionEvent.getAction()){
                    case MotionEvent.ACTION_DOWN:
                        iv_video.setImageResource(R.mipmap.video);
//                        if (mIsPlay) {
//                            if (mediaPlayer != null) {
//                                mIsPlay = false;
//                                mediaPlayer.stop();
//                                mediaPlayer.reset();
//                                mediaPlayer.release();
//                                mediaPlayer = null;
//                            }
//                        }
//                        if (!mStartedFlg) {
                            handler.postDelayed(runnable,1000);
//                            mImageView.setVisibility(View.GONE);
                            if (mRecorder == null) {
                                mRecorder = new MediaRecorder();
                            }

                            camera = Camera.open(Camera.CameraInfo.CAMERA_FACING_BACK);
                            if (camera != null) {
                                camera.setDisplayOrientation(90);
                                camera.unlock();
                                mRecorder.setCamera(camera);
                            }

                            try {
                                // 这两项需要放在setOutputFormat之前
                                mRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
                                mRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);

                                // Set output file format
                                mRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);

                                // 这两项需要放在setOutputFormat之后
                                mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
                                mRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.MPEG_4_SP);

                                mRecorder.setVideoSize(640, 480);
                                mRecorder.setVideoFrameRate(30);
                                mRecorder.setVideoEncodingBitRate(3 * 1024 * 1024);
                                mRecorder.setOrientationHint(90);
                                //设置记录会话的最大持续时间（毫秒）
                                mRecorder.setMaxDuration(30 * 1000);
                                mRecorder.setPreviewDisplay(mSurfaceHolder.getSurface());

                                path = getSDPath();
                                if (path != null) {
                                    File dir = new File(path + "/plant"+ MyApplication.VIDEO_PATH);
                                    if (!dir.exists()) {
                                        dir.mkdirs();
                                    }
                                    path = dir + "/" +MyApplication.GATHER_NUM+ ".mp4";
                                    mRecorder.setOutputFile(path);
                                    mRecorder.prepare();
                                    mRecorder.start();
                                    mStartedFlg = true;
//                                    mBtnStartStop.setText("Stop");
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
//                        } else {
                            //stop
//                            if (mStartedFlg) {
//                                try {
//                                    handler.removeCallbacks(runnable);
//                                    mRecorder.stop();
//                                    mRecorder.reset();
//                                    mRecorder.release();
//                                    mRecorder = null;
////                                    mBtnStartStop.setText("Start");
//                                    if (camera != null) {
//                                        camera.release();
//                                        camera = null;
//                                    }
//                                } catch (Exception e) {
//                                    e.printStackTrace();
//                                }
//                            }
//                            mStartedFlg = false;
//                        }
                        break;
                    case MotionEvent.ACTION_UP:
                        iv_video.setImageResource(R.mipmap.vides);

                            try {
                                handler.removeCallbacks(runnable);
                                mRecorder.stop();
                                mRecorder.reset();
                                mRecorder.release();
                                mRecorder = null;
//                                    mBtnStartStop.setText("Start");
                                if (camera != null) {
                                    camera.release();
                                    camera = null;
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        mStartedFlg = false;

                        Intent intent=new Intent();
                        intent.putExtra("videoPath",path);
                        Log.d("plant","videoPath:"+path);
                        setResult(RESULT_OK,intent);
                        finish();
                        break;
                }
                return false;
            }
        });
    }

    //播放视频
    private void playVideo(){
//        if (mRecorder == null) {
//            mRecorder = new MediaRecorder();
//        }
//
//        camera = Camera.open(Camera.CameraInfo.CAMERA_FACING_BACK);
//        if (camera != null) {
//            camera.setDisplayOrientation(90);
//            camera.unlock();
//            mRecorder.setCamera(camera);
//        }

        mIsPlay = true;
//        mImageView.setVisibility(View.GONE);
        if (mediaPlayer == null) {
            mediaPlayer = new MediaPlayer();
        }
        mediaPlayer.reset();
        Uri uri = Uri.parse(path);
        mediaPlayer = MediaPlayer.create(TestBasicVideo.this, uri);
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mediaPlayer.setDisplay(mSurfaceHolder);
        try{
            mediaPlayer.prepare();
        }catch (Exception e){
            e.printStackTrace();
        }
        mediaPlayer.start();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!mStartedFlg) {
//            mImageView.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 获取系统时间
     *
     * @return
     */
    public static String getDate() {
        Calendar ca = Calendar.getInstance();
        int year = ca.get(Calendar.YEAR);           // 获取年份
        int month = ca.get(Calendar.MONTH);         // 获取月份
        int day = ca.get(Calendar.DATE);            // 获取日
        int minute = ca.get(Calendar.MINUTE);       // 分
        int hour = ca.get(Calendar.HOUR);           // 小时
        int second = ca.get(Calendar.SECOND);       // 秒

        String date = "" + year + (month + 1) + day + hour + minute + second;
        Log.d(TAG, "date:" + date);

        return date;
    }

    /**
     * 获取SD path
     *
     * @return
     */
    public String getSDPath() {
        File sdDir = null;
        boolean sdCardExist = Environment.getExternalStorageState()
                .equals(android.os.Environment.MEDIA_MOUNTED); // 判断sd卡是否存在
        if (sdCardExist) {
            sdDir = Environment.getExternalStorageDirectory();// 获取跟目录
            return sdDir.toString();
        }

        return null;
    }

    @Override
    public void surfaceCreated(SurfaceHolder surfaceHolder) {
        mSurfaceHolder = surfaceHolder;
    }

    @Override
    public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
        // 将holder，这个holder为开始在onCreate里面取得的holder，将它赋给mSurfaceHolder
        mSurfaceHolder = surfaceHolder;
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
        mSurfaceview = null;
        mSurfaceHolder = null;
        handler.removeCallbacks(runnable);
        if (mRecorder != null) {
            mRecorder.release(); // Now the object cannot be reused
            mRecorder = null;
            Log.d(TAG, "surfaceDestroyed release mRecorder");
        }
        if (camera != null) {
            camera.release();
            camera = null;
        }
        if (mediaPlayer != null){
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }
}
